﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lua4Net;
using MessageSystem.Managed.Rpc;

namespace MessageSystem.Managed.LuaRpc
{
    public class LuaRpcRegister : LuaRegister
    {
        private static LuaCSFunction _call1     = LuaRpcRegister.ProxyCall1;
        private static LuaCSFunction _call2     = LuaRpcRegister.ProxyCall2;
        private static LuaCSFunction _create    = LuaRpcRegister.ProxyCreate;

        public override void Register(IntPtr l)
        {
            LuaApi.lua_pushstring(l, "ProxyCall1");
            LuaApi.lua_pushcfunction(l, _call1);
            LuaApi.lua_settable(l, (int)LuaIndex.LUA_GLOBALSINDEX);

            LuaApi.lua_pushstring(l, "ProxyCall2");
            LuaApi.lua_pushcfunction(l, _call2);
            LuaApi.lua_settable(l, (int)LuaIndex.LUA_GLOBALSINDEX);

            LuaApi.lua_pushstring(l, "ProxyCreate");
            LuaApi.lua_pushcfunction(l, _create);
            LuaApi.lua_settable(l, (int)LuaIndex.LUA_GLOBALSINDEX);
        }

        private static int ProxyCall1(IntPtr l)
        {
            int proxyId = (int)LuaApi.lua_tonumber(l,1);
            LuaProxy proxy = LuaManager.Instance.GetObjectT<LuaProxy>(proxyId);
            if(null != proxy)
            {
                LuaMessage request = new LuaMessage();
                int nMessageId = (int)LuaApi.lua_tonumber(l, 2);
                string sJson = LuaApi.lua_tostring(l, 3);
                proxy.Call(sJson, nMessageId);
            }
            return 0;
        }

        private static int ProxyCall2(IntPtr l)
        {
            int proxyId = (int)LuaApi.lua_tonumber(l, 1);
            LuaProxy proxy = LuaManager.Instance.GetObjectT<LuaProxy>(proxyId);
            if (null != proxy)
            {
                LuaMessage request = new LuaMessage();
                int nMessageId = (int)LuaApi.lua_tonumber(l, 2);
                string sJson = LuaApi.lua_tostring(l, 3);
                LuaRefFunction reffunc = new LuaRefFunction(4, l);
                LuaCallback callback = new LuaCallback(reffunc);
                proxy.Call(sJson, nMessageId, callback);
            }
            return 0;
        }

        private static int ProxyCreate(IntPtr l)
        {
            int domainId = (int)LuaApi.lua_tonumber(l,1);
            RpcDomain domain = LuaManager.Instance.GetObjectT<RpcDomain>(domainId);
            if(null != domain)
            {
                Int16 serviceId = (Int16)LuaApi.lua_tonumber(l,2);
                Int32 sessionId = (Int32)LuaApi.lua_tonumber(l,3);
                LuaProxy proxy = domain.CreateProxy<LuaProxy>(serviceId,sessionId,LuaInvoker.Instance,null);
                int proxyId = LuaManager.Instance.AddHeapObject(proxy);
                LuaApi.lua_pushnumber(l, proxyId);
                return 1;
            }
            return 0;
        }
    }
}
